<?php

namespace app\admin\controller\department;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 *
 */
class Role extends Backend
{

    protected $relationSearch = true;

    /**
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\department\Role;
    }


    public function excel()
    {
        if ($this->request->isPost()) {
            ini_set('memory_limit', '-1'); //设置为不限制
            set_time_limit(0);  //设置为不限制

            $fileName = input('pdf');
            $fileName = str_replace($_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["SERVER_NAME"], '', $fileName);
            $file = $_SERVER ["DOCUMENT_ROOT"] . $fileName;
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
            $reader->setReadDataOnly(true);  //过滤excel中的特殊字符
            $PHPExcel = $reader->load($file);
            $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
            $highestRow = $sheet->getHighestRow(); // 取得总行数
            $highestColumn = $sheet->getHighestColumn(); // 取得总列数
            $data = [];

            for ($row = 2; $row <= $highestRow; $row++) { //行号从1开始
                for ($column = 'A'; $column <= $highestColumn; $column++) { //列数是以A列开始
                    if (empty($sheet->getCell($column . $row)->getValue()) == false) {
                        $data[$row][$column] = $sheet->getCell($column . $row)->getValue();
                    }
                }
//                if (!isset($data[$row]['B'])) unset($data[$row]);
            }
//            halt($data);
            Db::startTrans();
            try {
                $typeArr = [];
                $j = 2;
                foreach ($data as $k => $v) {
                    $exits = $this->model->where('name', $v['A'])->value('id');
                    if (!empty($exits)) {
                        $this->error("第【{$j}】行的名称已存在，请删除后重试");
                    }
                    $j++;
                }
                foreach ($data as $k => $v) {
                    $res = [
                        "name" => $v['A'],

                    ];
                    $typeArr[] = $res;
                }
                $res = $this->model->saveAll($typeArr);

                Db::commit();
                $this->success();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

        }
        $doc = "/template/excel/角色列表导入模板.xlsx";
        $this->view->assign("doc", $doc);
        return $this->view->fetch();
    }

    /**
     * 下拉搜索
     */
    public function selectpage()
    {
        return parent::selectpage();
    }

}
